<template>
  <div class="plugin-container">
    <div v-loading="loading" class="min-h-screen-180">
      <WujieVue
        v-if="currentApp && currentApp.type === 'wujie'"
        width="100%"
        height="100%"
        :name="currentApp.name"
        :url="currentApp.url"
        :sync="true"
        :plugins="plugins"
        :before-load="onBeforeLoad"
        :before-mount="onBeforeMount"
        :after-mount="onAfterMount"
        :before-unmount="onBeforeUnmount"
        :after-unmount="onAfterUnmount"
        :loading="loading"
        @error="onWujieError"
      />
      <iframe class="w-full" :style="currentApp.style" v-else-if="currentApp &&currentApp.type==='iframe'" :src="currentApp.url" frameborder="0"></iframe>
      <div v-else-if="!loading && !currentApp" class="flex items-center justify-center h-96">11
        <el-empty description="未找到对应的应用配置" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import WujieVue from 'wujie-vue3'
import { useSettingsStore } from '@/stores/settings'

// 定义组件名称
defineOptions({
  name: 'CustomerPlugin'
})

const route = useRoute()
const settingsStore = useSettingsStore()

// 响应式数据
const loading = ref(true)
const appName = ref('')

// 计算属性
const customerMenu = computed(() => {
  // 优先使用hooks中的customer_menu_hook数据
  if (!settingsStore.hooksLoading && settingsStore.hooks.customer_menu_hook) {
    return settingsStore.hooks.customer_menu_hook || []
  }
  // 后备方案：使用旧的customerMenu数据
  return settingsStore.customerMenu || []
})
const currentApp = computed(() => {
  if (!customerMenu.value || !appName.value) return null
  const app = customerMenu.value.find((item) => item.name === appName.value)

  // 处理第三方网站的URL
  if (app && app.type === 'wujie' && app.url) {
    // 检查是否是外部URL
    if (app.url.startsWith('http://') || app.url.startsWith('https://')) {
      // 对于外部URL，可以考虑使用代理或降级为iframe
      const url = new URL(app.url)
      if (url.hostname !== window.location.hostname) {
        // 第三方网站，暂时降级为iframe处理
        return {
          ...app,
          type: 'iframe',
          style: 'height: calc(100vh - 180px);'
        }
      }
    }
  }

  return app
})

// wujie 插件配置
const plugins = ref([
  {
    // 修复固定定位元素的插件
    appendOrInsertElementHook: function (element, iframeWindow) {
      if (element.offsetParent && element.offsetParent.tagName !== 'BODY') {
        return
      }
      const offsetParentDesc = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetParent')
      Object.defineProperties(element, {
        offsetParent: {
          configurable: true,
          get: function () {
            const offsetParent = offsetParentDesc.get.call(this)
            if ((offsetParent && offsetParent.tagName !== 'BODY') || element.style.position !== 'fixed') {
              return offsetParent
            }
            return new Proxy(window.document.documentElement, {
              get: (target, propKey) => {
                if (propKey === 'parentNode') {
                  return iframeWindow.document.documentElement.parentNode
                }
                const value = target[propKey]
                const naughtySafari = typeof document.all === 'function' && typeof document.all === 'undefined'
                // 只有这些场景下才需要 bind
                if (
                  (naughtySafari ? typeof value === 'function' && typeof value !== 'undefined' : typeof value === 'function') &&
                  !(value.name.indexOf('bound ') === 0 && !Object.prototype.hasOwnProperty.call(value, 'prototype'))
                ) {
                  const boundValue = Function.prototype.bind.call(value, target)
                  for (const key in value) {
                    boundValue[key] = value[key]
                  }
                  if (
                    Object.prototype.hasOwnProperty.call(value, 'prototype') &&
                    !Object.prototype.hasOwnProperty.call(boundValue, 'prototype')
                  ) {
                    Object.defineProperty(boundValue, 'prototype', {
                      value: value.prototype,
                      enumerable: false,
                      writable: true
                    })
                  }
                  return boundValue
                }
                return value
              }
            })
          }
        }
      })
    }
  }
])

// wujie 生命周期钩子
const onBeforeLoad = (appWindow) => {
  console.log(`${currentApp.value?.name} 即将加载`, appWindow)
}

const onBeforeMount = (appWindow) => {
  console.log(`${currentApp.value?.name} 即将渲染`, appWindow)
}

const onAfterMount = (appWindow) => {
  console.log(`${currentApp.value?.name} 渲染完成`, appWindow)
  loading.value = false
}

// wujie 错误处理
const onWujieError = (error) => {
  console.error(`${currentApp.value?.name} 加载失败:`, error)
  // 对于加载失败的外部URL，可以考虑降级为iframe
  if (currentApp.value?.url && currentApp.value.url.startsWith('http')) {
    const url = new URL(currentApp.value.url)
    if (url.hostname !== window.location.hostname) {
      console.log('外部URL加载失败，降级为iframe处理')
      // 可以在这里触发重新渲染为iframe
    }
  }
}

const onBeforeUnmount = (appWindow) => {
  console.log(`${currentApp.value?.name} 即将卸载`, appWindow)
}

const onAfterUnmount = (appWindow) => {
  console.log(`${currentApp.value?.name} 卸载完成`, appWindow)
}

// 监听hooks数据变化
watch(
  () => settingsStore.hooksLoading,
  (isLoading) => {
    if (!isLoading && customerMenu.value.length > 0) {
      loading.value = false
    }
  },
  { immediate: true }
)

// 初始化应用
const initApp = async () => {
  loading.value = true
  appName.value = route.params.appName

  // 如果hooks数据已经加载完成，直接检查是否有菜单数据
  if (!settingsStore.hooksLoading && customerMenu.value.length > 0) {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.params.appName,
  (newAppName) => {
    if (newAppName) {
      appName.value = newAppName
    }
  },
  { immediate: true }
)

// 监听菜单数据变化
watch(
  customerMenu,
  (newMenu) => {
    if (newMenu && newMenu.length > 0 && !settingsStore.hooksLoading) {
      loading.value = false
    }
  },
  { immediate: true }
)

// 组件挂载
onMounted(() => {
  initApp()
})
</script>

<style scoped lang="scss">
.plugin-container {
  width: 100%;
  height: 100%;
}

.min-h-screen-180 {
  min-height: calc(100vh - 180px);
}
</style>
